import React, { PureComponent, Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Button, Row, Form, Input } from 'antd';
import { GlobalFooter } from 'ant-design-pro';
import ReactHelmet from 'react-helmet';
import config from '@/utils/config';
import { messErr } from '@/utils/message';

import styles from './index.less';

const FormItem = Form.Item;

@connect(({ loading }) => ({ loading }))
@Form.create()
class Login extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      type: 'signin', // signin || signup
    };
  }

  // 检查用户名是否合法，长度为11位
  checkUserNameValid = (username) => {
    if(!/^[0-9]{11}$/.test(username)) {
      messErr('手机号为11位数字');
      return false;
    }
    return true;
  };

  // 检查密码是否合法，长度为6位到25位
  checkPasswordValid = (password) => {
    if(!(password.length >= 6 && password.length <= 32)) {
      messErr('密码长度为6到32位');
      return false;
    }
    return true;
  };

  // 提交表单
  handleOk = () => {
    const {
      dispatch,
      form,
    } = this.props;
    const {
      type,
    } = this.state;
    const { validateFieldsAndScroll } = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return;
      }

      const {
        username,
        password,
        confirmpassword,
      } = values;

      if(!this.checkUserNameValid(username)) return false;
      if(!this.checkPasswordValid(password)) return false;

      if(type === 'signin') {
        dispatch({
          type: 'app/signInEffect',
          payload: {
            data: {
              username: username,
              password: password,
            },
          },
        });
      } else {
        if(password !== confirmpassword) {
          messErr('两次密码输入不一致!!');
          return;
        }
        dispatch({
          type: 'app/signUpEffect',
          payload: {
            data: {
              username,
              password,
            },
          },
        });
      }
    });
  };

  // 点击注册，进行注册的操作
  handleToggle = () => {
    const {
      type,
    } = this.state;
    if(type === 'signin') {
      this.setState({ type: 'signup' });
    } else {
      this.setState({ type: 'signin' });
    }
  };

  render() {
    const { loading, form } = this.props;
    const { getFieldDecorator } = form;
    const {
      type,
    } = this.state;

    return (
      <Fragment>
        <ReactHelmet>
          <title>
            {type === 'signin' ? '登录' : '注册'}
          </title>
        </ReactHelmet>
        <div className={styles.form} style={{ height: type === 'signin' ? 320 : 380 }}>
          <div className={styles.logo}>
            <img alt="logo" src={config.logoPath}/>
            <span>{config.siteName}</span>
          </div>
          <form>
            <FormItem hasFeedback>
              {getFieldDecorator('username', {
                rules: [
                  {
                    required: true,
                    message: '用户名不符合规范',
                  },
                ],
              })(
                <Input
                  onPressEnter={this.handleOk}
                  placeholder="手机号"
                  maxLength={11}
                  autoComplete="on"
                />,
              )}
            </FormItem>
            <FormItem hasFeedback>
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: '密码不符合规范',
                  },
                ],
              })(
                <Input
                  type="password"
                  onPressEnter={this.handleOk}
                  placeholder="密码"
                  maxLength={32}
                />,
              )}
            </FormItem>
            {type === 'signup' && (
              <FormItem hasFeedback>
                {getFieldDecorator('confirmpassword', {
                  rules: [
                    {
                      required: type === 'signup',
                      message: '确认密码不能为空',
                    },
                  ],
                })(
                  <Input
                    type="password"
                    onPressEnter={this.handleOk}
                    placeholder="确认密码"
                    maxLength={32}
                  />,
                )}
              </FormItem>
            )}
            <Row>
              <Button
                type="primary"
                onClick={this.handleOk}
                loading={loading.effects.login}
              >
                {type === 'signin' ? '登录' : '注册'}
              </Button>
              <p className={styles.bottomWrapper}>
                <span className={styles.toggle} onClick={this.handleToggle}>
                  {type === 'signin' ? '注册' : '登录'}
                </span>
              </p>
            </Row>
          </form>
        </div>
        <div className={styles.footer}>
          <GlobalFooter copyright={config.copyright} />
        </div>
      </Fragment>
    );
  }
}

Login.propTypes = {
  form: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
};

export default Login;
